import { _decorator, Component, Node, Prefab, NodePool, instantiate } from 'cc';
const { ccclass, property } = _decorator;

// 
interface IDictPool {
    [name: string]: {
        prefab: Prefab,
        pool: NodePool,
    }
}
@ccclass('PoolManager')
export class PoolManager {
    public static instantiate() {
        if(!this._instance){
            this._instance = new PoolManager()
        }
        return this._instance
    }

    private _dictPool: IDictPool = {}
    // 自身实例对象
    private static _instance: PoolManager

    // 回收到节点池
    public putNode(node: Node) {
        let name = node.name
        node.parent = null
        // 如果没有对应节点池则创建一个
        if(!this._dictPool[name]) {
            this._dictPool[name] = {
                prefab: null,
                pool: new NodePool()
            }
        }
        this._dictPool[name].pool.put(node)
    }

    // 获取节点
    public getNode(prefab: Prefab, parent: Node) {
        let name = prefab.data.name
        let node: Node = null
        const poolItem = this._dictPool[name]
        if (poolItem) {
            if (poolItem.pool.size() > 0) {
                // 如果有这个节点池并且其中有节点则直接从节点池中取
                node = poolItem.pool.get()
            } else {
                // 节点池中没有节点，则实例化一个
                node = instantiate(prefab)
            }
        } else {
            // 没有这个节点池，创建一个节点池
            this._dictPool[name] = {
                prefab: prefab,
                pool: new NodePool()
            }
            // 实例化一个节点
            node = instantiate(prefab)
        }
        // 设置父节点，并激活
        node.parent = parent
        node.active = true
        return node
    }
}

